<template>
  <div>


    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="10" class="mb8" style="width:80%;margin:20px auto">
        <el-col :span="1.5">
          <!--  -->
          <el-button type="success" plain icon="el-icon-top" @click="handleAdd()"
            v-hasPermi="['archive:supervision:supervises:add']">保存</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button plain icon="el-icon-document-copy" @click="resetting()">重置</el-button>
        </el-col>
      </el-row>
      <el-row ref="refbut" style="width:80%;margin:0 auto">
        <el-col :span="24" class="df transf-title-row">

          <el-form-item label="指导人">
            {{ form.mentor }}
          </el-form-item>


        </el-col>
        <el-col :span="24" class="df transf-title-row">

          <el-form-item label="">
            <span slot="label">
              <em style="color:red"> * </em>
              指导建议
            </span>
            <!-- <editor v-model="form.suggestions"  :min-height="400"/> -->
            <editor v-model="form.suggestions" style="width: 100%" accept=".png, .jpg, jpeg" :isMaterialList="true"
              :isMaterialListStyle="'2'" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="上传附件">
            <!--           　<el-button class="upload_btn" size="medium" type="primary" icon="el-icon-upload">上传文件</el-button>-->
            <div style="display: flex; flex-wrap: wrap; /* 允许子元素换行 */">
              <el-button class="upload_btn" type="primary" icon="el-icon-upload"  v-if="fileMJ == undefined && isFbState"
                @click="uploadTap">上传文件</el-button>
              <el-upload v-else class="upload-file-demo" action="上传的url" ref="uploadComp" :auto-upload="true"
                :show-file-list='false' :on-change="handleChange" :disabled="loading" accept="" :http-request="uploadFile"
                :file-list="fileList">
                <div style="width: 100%; display: flex">
                  <el-button :loading="loading" type="primary" icon="el-icon-upload">上传文件</el-button>
                </div>
              </el-upload>
              <el-select v-if="isFbState" style="margin-left:10px;" v-model="fileMJ" placeholder="请选择文件密级" @change="selectChange($event)">
                <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                  :value="item.dictValue"></el-option>
              </el-select>
              <div v-for="item in uploadList" style="display: flex; margin-left: 1%" :key="item">
                <span style="padding: 0 5px">{{ item.docName }}</span>
                <p v-if="isFbState" style="border-bottom: 1px solid red;">
                      <span v-for="(i, idx) in renyuanOptions" :key="idx">
                        {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                      </span>
                    </p>
                <el-button type="text" @click="onPreviewTap(item)" style="margin-left:10px">预览</el-button>
                <el-button type="text" style="color: #ff0000" @click="deleteTap(item)">删除</el-button>
              </div>
            </div>
          </el-form-item>


        </el-col>
      </el-row>



    </el-form>
    <el-row :gutter="10" class="mb8" style="width:90%;margin:0 auto;margin-bottom:20px">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" @click="handleDelete">移除</el-button>
      </el-col>
    </el-row>
    <el-table height="300" style="width:90%;margin:0 auto" v-loading="loading" :data="dataList" :row-key="getRowKeys"
      :expand-row-keys="expands" @cell-dblclick="celldblclick" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" sortable align="center" type="index" />
      <el-table-column type="expand">
        <template slot-scope="props" v-if="props.row.children.length > 0">
          <el-table :data="props.row.children" style="width:88%;margin-left:10%" border>
            <el-table-column label="档号" align="center" prop="dh" :show-overflow-tooltip="true" />
            <el-table-column label="题名" align="center" prop="title" :show-overflow-tooltip="true" />
            <el-table-column label="档案门类" align="center" prop="categoryCode"
              :show-overflow-tooltip="true"></el-table-column>
            <!-- <el-table-column label="密级" v-if="isFbState">
              <template slot-scope="scope">
                <el-select v-model="scope.row.MJ" placeholder="请选择文件密级">
                  <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                    :value="item.dictValue"></el-option>
                </el-select>
              </template>
            </el-table-column> -->
            <el-table-column label="全宗号" align="center" prop="qzh" :show-overflow-tooltip="true" />
            <el-table-column label="分类" align="center" prop="type" width="120">
              <template slot-scope="scope">
                <p v-if="scope.row.type == 1">
                  组卷
                </p>
                <p v-if="scope.row.type == 0">
                  组件
                </p>
              </template>
            </el-table-column>
            <el-table-column label="来源" align="center" prop="source" width="120">
              <template slot-scope="scope">
                <p v-if="scope.row.source == '1'">
                  档案整理
                </p>
                <p v-if="scope.row.source == '0'">
                  文件整理
                </p>
              </template>
            </el-table-column>
            <el-table-column label="添加时间" align="center" prop="createTime" width="160" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="档号" align="center" prop="dh" :show-overflow-tooltip="true" />
      <el-table-column label="题名" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="档案门类" align="center" prop="categoryCode" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="全宗号" align="center" prop="qzh" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" prop="type" width="120">
        <template slot-scope="scope">
          <p v-if="scope.row.type == 1">
            组卷
          </p>
          <p v-if="scope.row.type == 0">
            组件
          </p>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source" width="120">
        <template slot-scope="scope">
          <p v-if="scope.row.source == '1'">
            档案整理
          </p>
          <p v-if="scope.row.source == '0'">
            文件整理
          </p>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" width="160" />


    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <!--
       文件预览
       1、修改添加文件预览istype="1"
       2、查看组件详情istype="2"
       -->
      <FilePreview v-if="item" :item="item" :istype="istype"></FilePreview>
    </el-dialog>

    <!--start  组件详情 -->
    <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen" :celldbData="celldbData"
      @detailsHandleClose="detailsHandleClose">
    </jianDetailsOpen>
    <!--end 组件详情 -->
    <!-- start 组卷\项目详情 -->
    <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData"
      @detailsHandleClose="detailsHandleClose"></juanDetailsOpen>
    <!-- end 组卷\项目详情 -->
  </div>
</template>

<script>


import estimateTableHeight from '@/mixins/estimateTableHeight'
import {
  listDaList,
  deleteDa,
  getUserMessage,
  addSupervision,
  uploadFile, uploadFileList, deleteFile, daList
} from "@/api/archive/supervision/supervises/supervises";
import FilePreview from "@/views/archive/supervision/supervises/filePreview";
import { getLastIndexOf } from "@/utils";
import { getthbytreenodeHeaderList } from "@/api/archive/warehouseManagement/upDownShelves";
import jianDetailsOpen from "@/components/componentsJianDetails";
import juanDetailsOpen from "@/components/componentsJuanDetails";

import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
  getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
  components: { FilePreview, jianDetailsOpen, juanDetailsOpen },
  mixins: [estimateTableHeight], // 混入方法

  data() {
    return {
      form: {
        id: undefined,
        suggestions: undefined,
        mentor: undefined,
        daIds: undefined
      },
      loading: false,
      dataList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      dataId: "",
      noClick: true,
      rules: {
        suggestions: [
          { required: true, message: "指导建议不能为空", trigger: "blur" }
        ]
      },
      fileList: [],
      uploadList: [],

      // 预览标题
      title: '',
      open: false,
      item: '',
      istype: '1',
      // 获取row的key值
      getRowKeys(row) {
        return row.id;
      },
      // 要展开的行，数值的元素是row的key值
      expands: [],
      jianDetailsOpen: false,//件详情弹窗
      juanDetailsOpen: false,//卷详情弹窗
      renyuanOptions: [],//密级下拉列表
      isFbState: false,
      fileMJ: undefined,
    }
  },
  created() {
    this.getUserMessage();
    this.getList();
    this.uploadList = []
    fbstat().then(res => {  //false=不是分保，true=是分保 
      this.isFbState = res.data
      if (this.isFbState) {
        //密级下拉列表
        getDicts_archive("MJ").then(res => { //人员密级
          getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
            console.log(resdata, "------------------------")
            var mjdata = [];
            for (var i in resdata.data) {
              for (var j in res.data) {
                if (resdata.data[i].daMj == res.data[j].dictValue) {
                  mjdata.push(res.data[j])
                }
              }
            }

            this.renyuanOptions = mjdata
            console.log(this.renyuanOptions, "------------------------------------------")

          })
        })
      }
    })
  },
  methods: {
    getList() {
      this.loading = true;
      listDaList(this.queryParams).then(response => {
        this.dataList = response.rows;
        for (let i = 0; i < this.dataList.length; i++) {
          daList({ daId: this.dataList[i].daId }).then(res => {
            this.dataList[i].children = res.rows
          })
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }   // 删除按钮
    , handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(function () {
        return deleteDa(id)
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => { });
    }, getUserMessage() {
      this.loading = true;
      getUserMessage().then(response => {
        this.form.id = response.data.id;
        this.form.mentor = response.data.mentor;
        this.loading = false;
      });
    }, handleAdd(row) {
      //保存<p><br></p>
      if (this.form.suggestions == undefined || this.form.suggestions == '<p><br></p>') {
        this.$modal.msgWarning("请填写指导建议！");
        return false;
      }
      if (this.noClick) {
        this.noClick = false
        console.log(this.form.suggestions, "2342343")

        this.form.daIds = this.ids.join(",");
        addSupervision(this.form).then(response => {

          this.$modal.msgSuccess("新增成功");
          this.reset();

          this.getUserMessage();
          this.getList();
          this.uploadList = []
          setTimeout(() => {
            this.noClick = true
          }, 800)
        }).catch(() => {
          setTimeout(() => {
            this.noClick = true
          }, 800)
        })


      }

    }, reset() {
      this.form = {
        id: undefined,
        suggestions: undefined,
        mentor: undefined,
        daIds: undefined
      }
    }, resetting() {
      this.reset();
      this.getUserMessage();
      this.getList();
    },
    // 文件上传 - 文件选中后上传
    handleChange(file, fileList) {
      /* 自动上传改成true会导致重复触发，所以在handleChange上传文件*/
      //  防抖
      let length = fileList.length
      this.fileList = fileList
      this.maxLength = Math.max(length, this.maxLength)
      setTimeout(() => {
        if (length === this.maxLength) {
          // 你的上传文件逻辑
          this.$refs.uploadComp.submit();
        }
      }, 100)
    },
    uploadTap() {
      if (this.fileMJ == undefined) {
        this.$message.warning(`请选择密级`);
        return false
      }
    },
    //上传文件MJ类型的下拉框
    selectChange(event) {
      // this.uploadData["mj"] = this.fileMJ
    },
    //开始上传文件
    uploadFile(content) {
      this.file = content.file
      const formData = new FormData();
      formData.append("file", content.file);
      formData.append("id", this.form.id);
      if(this.isFbState){
        formData.append("mj", this.fileMJ);
      }
      uploadFile(formData).then(response => {
        this.getFileList()
      })
    },
    getFileList() {
      uploadFileList({ supervisionId: this.form.id }).then(response => {
        this.uploadList = response.rows
      })
    },
    // 预览
    onPreviewTap(item) {
      this.title = item.docName
      this.open = true
      this.item = item
    },
    // 删除
    deleteTap(item) {
      this.$modal.confirm('是否确认删除名为"' + item.docName + '"的附件？').then(function () {
        return deleteFile(item.id);
      }).then(() => {
        this.getFileList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => { });
    },
    //关闭详情页面
    detailsHandleClose() {
      this.jianDetailsOpen = false;
      this.juanDetailsOpen = false;
    },
    celldblclick(row) {
      console.log(row, '------------------')
      var level = "";
      if (getLastIndexOf(row.subTableName) == "F") {  //F 件
        level = 0
      } else if (getLastIndexOf(row.subTableName) == "V") { //卷
        level = 1
      } else { //项目
        level = 3
      }
      const menuId = this.$route.meta.menuId
      getthbytreenodeHeaderList(
        {
          categoryId: row.categoryId, menuId: menuId, subTableName: row.subTableName
        }
      ).then(response => {
        var tableHeaderList = response.rows
        this.celldbData = {
          id: row.daId,
          categoryId: row.categoryId,
          menuId: menuId,
          sub_table_name: row.subTableName,
          label: row.title,
          level: level,
          ifSub_table_name: row.subTableName,
          isDel: "0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
          tableHeaderList: tableHeaderList
        }
        this.$nextTick(() => {
          if (getLastIndexOf(row.subTableName) == "F") {  //F 进入件详情
            this.jianDetailsOpen = true;
          } else { //进入卷详情 和项目详情
            this.juanDetailsOpen = true
          }
        })
      })
    },
  }
};
</script>

<style lang="scss" scoped>
.list-item {
  font-size: 18px;
  line-height: 50px;
  height: 50px;
  width: 45%;
  display: inline-block;
  margin-right: 20px;
  /* 可根据需要调整元素之间的间距 */
}

.list-item label {
  width: 100px;
  text-align: right;
  margin-right: 10px;
}

.upload-file-demo {
  width: 10%
}
</style>
